<template>
    <div>
      <!--<header-tilte :title="title"></header-tilte>-->
      <div class="header flex">
        <div style="width: 10%" @click="toMall()">
          <img style="width: 1.25rem;height: 1.25rem" src="../../assets/img/left.png">
        </div>
        <div style="width: 80%">
          <span>{{title}}</span>
        </div>
        <div style="width: 10%"></div>
      </div>
      <div class="flex_center">
        <div class="bodyContent">
          <default-address v-on:childByValue="childByValue"></default-address>
          <pay-type-choose v-on:radioValue="radioValue"></pay-type-choose>

          <div class="margin_top">
            <div class=" white_bac pading1 order_goods flex order_border_bom" v-for="(goods,index) in itemCartGoodsList">

              <img :src="goods.goods_img">
              <div class="goods_width">
                <p class="flex flex_between ">
                  <span class="goods_name">{{goods.goods_name}}</span>
                  <img @click="deleteGoodsCart(goods,index)"  src="../../assets/img/delete.png">
                </p>
                <p class="flex flex_between " style="color: #e6ca96"><span>￥ {{goods.goods_price}}</span> <span>x {{goods.count}}</span></p>
                <div class="flex flex_between">
                  <div class="flex flex_vertical_center">
                    <mu-switch @click="isWaterBillPay(goods)" v-if="WaterBillList[goods.id] != undefined" v-model="goods.choose_waterBill" label="水票支付" label-left></mu-switch>
                  </div>
                  <div class="add_minus flex_center">
                    <img src="../mall/img/minus-circle.png" @click="minusGoodsCount(goods)" v-if="goods.count > 1">
                    <img src="../../assets/img/2.png" v-if="goods.count <= 1">
                    <span>{{goods.count}}</span>
                    <img src="../mall/img/add.png" @click="addGoodsCount(goods)">
                  </div>
                </div>
              </div>
            </div>
          </div>
          <div class="margin_top white_bac pading1 order_foot margin_bot">
            <input type="text" style="font-size: 12px" placeholder="给商家留言" v-model="description">
            <p>本店总计：￥<span>{{allMoney}}</span></p>
          </div>
        </div>
      </div>
      <div class="accounts_foot flex flex_end">
        <p>合计支付：<span>{{allMoney}}元</span></p>
        <button class="sure_bottom disable_buttom" @click="setAccounts()">
          结算
        </button>
      </div>
    </div>
</template>

<script>


    import DefaultAddress from "../../components/components/DefaultAddress";
    import PayTypeChoose from "../../components/components/PayTypeChoose"
    export default {
      components: {
        DefaultAddress,
        PayTypeChoose},
      name: "build_order",
      data(){
        return{
          title:'填写订单',
          docked: false,
          open: false,
          position: 'right',
          addressChoosed:'',
          has_waterBill:0,//表示无水票 1表示有水票
          pay_type:'heart',//表示无水票 或不选择水票  1表示有水票或者选择水票
          pay_type1:[],
          radio: 0,
          tabs: ["微信支付",'货到付款'],
          itemCartGoodsList:  JSON.parse(this.getCache(this.getKey('itemCartList'))),//JSON.parse(localStorage.getItem('itemCartList')),
          WaterBillList:'',
          satus:true,
          setItem:0, //判断是否需要将生成的列表放入到缓存中
          setAllMoney:0,//判断是否计算总价格
          allMoney:0,
          editorStatus:false,
          description:'',
          allCount:0,
          min_num:null,
          max_num:null,

        }
      },
      mounted(){
        this.checkLogin();
        this.initH();
        this.initCartGoodsList();
        this.checkNum();
        /*this.initWaterBillList();*/
        this.$nextTick(function () {
          $('.mu-radio-label').css('font-size','14px')
        });


      },
      methods:{
        initH(){
          var allH = document.documentElement.clientHeight;
          var headerH = $('.header').height();
          var footH = $('.accounts_foot ').height();
          var h = allH - headerH - footH;
          $('.bodyContent').css('height',h + 'px');
        },

        radioValue: function (childValue) {
          this.radio = childValue;
        },
        initCartGoodsList(){
          var obj = this.getCache(this.getKey('itemCartList'));//localStorage.getItem('itemCartList');

          this.itemCartGoodsList = JSON.parse(obj);
          if(this.itemCartGoodsList == undefined ||
            this.itemCartGoodsList == null ||
            this.itemCartGoodsList == '' ||
            this.itemCartGoodsList.length <= 0){
            this.$alert('暂无可结算商品，请前往商城', '提示', {
              okLabel: '知道了'
            }).then(() => {
              this.$router.push({path:'/qds/mall'})
              return;
            });
          }else {
            var ids = [];
            for(var i=0;i<this.itemCartGoodsList.length;i++){
              ids.push(this.itemCartGoodsList[i].id);
              this.allCount += this.itemCartGoodsList[i].count;
            }

            this.initWaterBillList(ids);
          }
        },


        minusGoodsCount(obj){
          obj.count--;
          this.allCount--;
          this.setItem++;
          this.setAllMoney++;
        },
        addGoodsCount(obj){
          if(this.WaterBillList[obj.id]!=undefined && this.WaterBillList[obj.id] != null && this.WaterBillList[obj.id] != ''){
            if(obj.choose_waterBill){
              //判断是否到了水票购买上限
              var num = this.WaterBillList[obj.id].rest_num;
              if(obj.count >= num){
                this.$toast.message('您没有足够的水票');
                return;
              }
            }
          }
          obj.count ++;
          this.allCount++;
          this.setItem++;
          this.setAllMoney++;
        },
        initWaterBillList(ids){
          this.yesS.myBillList(
            this.$combineParams({'ids':ids})
          ).then(res => {
            var list = res.data.waterbill_list;

            if(list != undefined && list != null && list != ''){
              for(var i=0;i<this.itemCartGoodsList.length;i++){
                var goods = this.itemCartGoodsList[i];
                goods.bill_id = null;
                if(list[goods.id] != undefined && list[goods.id] != null && list[goods.id] != ''){
                  goods.bill_id = list[goods.id].id;//水票的id
                  goods.setAllMoney = 0; //表示结算时，不需要算价钱
                  this.setAllMoney++;
                  let num = list[goods.id].rest_num;
                  if(goods.count > num){
                    goods.count = num;
                    this.setItem++;
                    this.setAllMoney++;
                  }
                }
              }
              this.WaterBillList = list;
            }else {
              this.setAllMoney++;
            }
          })
        },

        //判断是否需要用水票支付（有水票的情况下）
        isWaterBillPay(obj){
          //判断当前数量是否在水票数量范围内

          var rest_num = this.WaterBillList[obj.id].rest_num;
          if(obj.count > rest_num){
            obj.count = rest_num;
          }
          if(obj.choose_waterBill == false){
            obj.setAllMoney = 1;
          }else {
            obj.setAllMoney = 0;
          }

          this.setAllMoney++;
        },
        _editoryGoodsCart(){
          this.editorStatus = !this.editorStatus
        },
        deleteGoodsCart(obj,index){
          this.$confirm('您将不再为该商品付款，并从购物车删除，是否继续操作？', '提示', {
            type: 'warning'
          }).then(({ result }) => {
            if (result) {

              this.itemCartGoodsList.splice(index, 1);
              this.allCount -= obj.count;
              this.setItem++;
              this.setAllMoney++;
            }
          });
        },


        setAccounts(){
          //判断是否有地址
          if(this.addressChoosed == undefined || this.addressChoosed == null || this.addressChoosed == ''){
            this.$toast.error('还未填写地址，请点击填写');
            return;
          }
          if(this.allMoney == undefined || this.allMoney == null || this.allMoney == ''|| this.allMoney <= 0){
            this.$confirm('请重新选择所需商品？', '提示', {
              type: 'warning'
            }).then(({ result }) => {
              if (result) {
                this.$router.push({path:'/qds/mall'})
                return;
              }
            });
          }
          //判断是否符合购买限量
          var content ='';
          if(this.max_num >0 && this.allCount > this.max_num){
            //判断购买的商品数量是否超过最大购买数量
            content =  '最高购买数量为 '+ this.max_num +' 件';
          }
          if(this.min_num >= 1 && this.allCount < this.min_num){
            content = '最低购买数量为 ' + this.min_num +' 件';
          }
          if(this.isEmpty(content)){
            //如果满足则
            this.sureBuyEnd();
          }else {
            this.$toast.error(content);
            return;
          }

        },
        checkNum(){
          this.yesS.checkBuyNum(
            this.$comParams()
          ).then(res => {
            var buyInfo = res.data.buy_info;

            //如果不在限量中则提示

            this.min_num = buyInfo.buy_min;
            this.max_num = buyInfo.buy_max;

          })
        },
        sureBuyEnd(){
          var endGoods = {};
          if(!this.isEmpty(this.itemCartGoodsList) && this.itemCartGoodsList.length > 0){
            for(var i=0;i<this.itemCartGoodsList.length;i++){
              var itemCart = this.itemCartGoodsList[i];
              endGoods[itemCart.goods_id] = {id:itemCart.goods_id,num:itemCart.count,bill_id:itemCart.bill_id == undefined?null:itemCart.bill_id}
            }
          }
          console.log(endGoods)
          var addressDetail = this.addressChoosed.area_info+' '+this.addressChoosed.position_address+this.addressChoosed.address;
          this.yesS.addOrderWbGoods(
            this.$combineParams({
              goods_list:endGoods,
              money:this.allMoney,
              pay_type:this.radio,//0 表示微信  1表示货到付款
              buyer_name:this.addressChoosed.name,
              mobile:this.addressChoosed.mobile,
              buyer_address:addressDetail,
              description:this.description
            })).then(res => {
              var status = res.status;
              if(status == 1){
                this.deleteCache(this.getKey('itemCartList'));
                /*this.endGoodsList = {};
                this.evaluateGoodsList();*/

                //成功后判断当前的支付方式
                if(!this.isEmpty(this.allMoney) && this.allMoney > 0){
                  if(this.radio == 1){
                    //跳转到支付成功页面 查看订单
                    this.$router.push({path:'/qds/success',query:{toType:1}})
                  }else if(this.radio == 0){
                    //调起微信支付
                    this.payment(res.data);
                  }
                }
              }
            }).catch(res => {
              //跳转到失败页面 返回到商城页
            this.$router.push({path:'/qds/fail',query:{toType:3}});
          })
        },
        payment(data) {

            this.wxPay(data, 1);

        },
        isPaySuccess(data){
          this.yesS.isPaySuccess(
            this.$combineParams({id:data.id})
          ).then(res => {
            var status = 0;
            if (res.data.result != undefined) {
              status = res.data.result;
            }
            if (status) {
              this.$router.push({path:'/qds/success',query:{toType:1}});
            } else {
              this.$router.push({path:'/qds/fail',query:{toType:3}});
            }
          }).catch(res => {
            this.$toast.error('支付失败，请稍后再试')
          })
        },
        childByValue: function (childValue) {
          // childValue就是子组件传过来的值
          this.addressChoosed = childValue;
        },
        toMall(){
          this.$router.push({
            path:'/goods'
          })
        }
      },
      watch:{
        setItem:{
          handler(curVal,oldVal){
            this.setCache(this.getKey('itemCartList'), JSON.stringify(this.itemCartGoodsList))
          },
          deep:true
        },
        setAllMoney:{
          handler(curVal,oldVal){
            var allMoney = 0;
            var goodsList = this.itemCartGoodsList;
            for(var i=0;i<goodsList.length;i++){
              if(goodsList[i].setAllMoney == 1){ //表示计算价钱的项
                allMoney += goodsList[i].goods_price * goodsList[i].count;
              }
            }
            this.allMoney = allMoney;

          },
          deep:true
        },
        allCount:{
          handler(curVal,oldVal){

          },
          deep:true
        }
      },
    }
</script>

<style scoped>
  @import "css/build_order.css";
  /*@import 'http://cdn.bootcss.com/material-design-icons/3.0.1/iconfont/material-icons.css';*/
  .header{
    width: 100%;
    padding: 0.5rem;
    display: flex;
    display: -webkit-flex;
    justify-content: center;
    -webkit-justify-content: center;
    align-items: center;
    -webkit-align-items: center;
    border-bottom: 1px solid #c3c3c3;
    background: #fff;
    position: relative;
  }
  .header img{
    width: 1.25rem;
    height: 1.25rem;
  }
</style>
